import React, { useState, useContext, useEffect } from 'react'
import Header from '../../components/Header/Header'
import { Button, SwipeAction, Dialog, Toast } from 'antd-mobile';
import { reqcartadd, reqcartdelete, reqcartedit, reqcartlist } from '../../http/api'
import { $pre } from '../../http/http';
import yImg from '../../assets/img/y.jpeg'
import nImg from '../../assets/img/n.jpeg'
import './Shop.less'
import { filterPrice } from '../../filters';
import { MyContext } from '../../App'

export default function Shop(props) {
  const [arr, setArr] = useState([])
  const { state: { userInfo: { uid } } } = useContext(MyContext)
  const [allchecked,setAllchecked]=useState(false)


  //请求列表
  useEffect(() => {
    getcar();
  }, [])

  let getcar = () => {
    let uid = JSON.parse(sessionStorage.getItem('userInfo')).uid;
    reqcartlist({ uid }).then(res => {
      let list = res.data.list[1].content ? res.data.list[1].content : [];
      list.forEach(item => {
        let obj = arr.find(i => i.id === item.id);
        item.checked = obj ? obj.checked : false;
      })
      setArr(list);
    })
  }

  //数量+
  let add = (id) => {
    reqcartedit({ id: id, type: 2 }).then(res => {
      if (res.data.code == 200) {
        Toast.show({
          content: res.data.msg
        })
        getcar()
      }
    })
  }

  //数量-
  let sub = (id, num) => {
    if (num > 1) {
      reqcartedit({ id: id, type: 1 }).then(res => {
        if (res.data.code == 200) {
          Toast.show({
            content: res.data.msg
          })
          getcar()
        }
      })
    } else {
      Toast.show({
        content: '宝贝不能再少了'

      })
    }
  }

  //删除
  let del = (id) => {
    reqcartdelete({ id: id }).then(res => {
      if (res.data.code === 200) {
        Toast.show({
          content: res.data.msg
        })
        getcar()
      }
    })
  }

//全选
  const changeAll = () => {
    let val = !allchecked;
    setAllchecked(val)
    arr.forEach((item)=>{
      item.checked=val
    })
    setArr(arr)
  }
  const changeOne=(index)=>{
    let checked=!arr[index].checked

    arr[index].checked=checked

    //放回去
    setArr([...arr])
    let newAllChecked = arr.every(item=>item.checked)
    setAllchecked(newAllChecked)
  }


  let allPrice = arr.reduce((v, i) => (i.checked ? v + i.price * i.num : v), 0)
  return (

    <div>
      <Header title='购物车'></Header>
      {arr.map((item, index) => (
        <SwipeAction
          key={item.id}
          closeOnAction={false}
          closeOnTouchOutside={false}
          rightActions={[
            {
              key: 'delete',
              text: '删除',
              color: 'danger',
              onClick: async () => {
                await Dialog.confirm({
                  content: '确定要删除吗？',
                  onConfirm: () => { del(item.id) }
                })
              },
            },
          ]}
        >
          <div className='item' >
            <img className='checkbox' src={item.checked ? yImg : nImg} alt="" />
            <img className='img' onClick={() =>changeOne(index)} src={$pre + item.img} alt="" />
            <div className='right'>
              <h3>name:{item.goodsname}</h3>
              <div>price:{filterPrice(item.price)}</div>
              <div>
                <Button onClick={() => sub(item.id, item.num)}>-</Button>
                {item.num}
                <Button onClick={() => add(item.id)}>+</Button>
              </div>
            </div>

          </div>
        </SwipeAction>
      )
      )}
      {/* 全选总价 */}
      <div className='footer'>
        <div className='allChecked' onClick={() => changeAll()}>
          
          <img className='checkbox' src={allchecked ? yImg : nImg} alt="" />全选
        </div>
        <div className='allPrice'>￥{filterPrice(allPrice)}</div>

      </div>

    </div>
  )
}
